import pickle

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By as seleniumBY
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as seleniumEC

from info import Info


class Kdriver:
    def __init__(self):
        driver = webdriver.Chrome(executable_path=Info.driver_path)
        driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
            'source': '''
                Object.defineProperty(navigator, 'webdriver', {
                  get: () => undefined
                })
              '''
        })
        self.driver = driver

    # def wait_element_load(self, element, expiration_time=10, **keywargs):
    #     while not self.is_exist(element, **keywargs):
    #         expiration_time -= 2
    #         if expiration_time < 0:
    #             return False
    #         sleep(2)
    #     return True

    def wait_element_load(self, element, expiration_time=10, **kwargs):
        try:
            WebDriverWait(self.driver, expiration_time)\
                .until(seleniumEC.presence_of_element_located((seleniumBY.CSS_SELECTOR,element)))
        except TimeoutError:
            return False
        if len(kwargs) > 0:
            return self.is_exist(element, **kwargs)
        return True

    def is_exist(self, element, **keywargs):
        flag = True
        try:
            target_element = self.driver.find_element_by_css_selector(element)
            if len(keywargs) > 0:
                for k,v in keywargs.items():
                    if getattr(target_element,k) != v:
                        raise NoSuchElementException
            return flag
        except NoSuchElementException:
            flag = False
        return flag

    def load_cookie(self, cookie):
        self.driver.delete_all_cookies()
        with open(Info.cookie_path, 'rb') as ck:
            cookies = pickle.load(ck)
        for cookie in cookies:
            self.driver.add_cookie(cookie)

